<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>取消请求</title>
    <link crossorigin='anonymous' href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="../node_modules/axios/dist/mine-axios.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <div class="container">
        <h2 class="page-header">axios取消请求</h2>
        <button class="btn btn-primary"> 发送请求 </button>
        <button class="btn btn-warning"> 取消请求 </button>
    </div>
    <script type="text/javascript">
        /* json-server命令：json-server --watch db.json --d 2000 */
        let cancel = null;
        $(".btn-primary").click(function () {
            // 检测上一次请求是否已经完成
            if (cancel !== null) {
                // 如果已完成，则取消上一次的请求
                cancel();
            }

            axios({
                method: 'GET',
                url: 'http://localhost:3000/posts',
                cancelToken: new axios.CancelToken((c)=>{
                    cancel = c;
                })
            }).then(resp => {
                console.log(resp);
                //将cancel的值恢复初始化
                cancel = null;
            });
            return false;
        });

        $(".btn-warning").click(function () {
            cancel();
            return false;
        });
    </script>
</body>
</html>